package team.kirohuji.config;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;

import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSubjectFactory;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import team.kirohuji.shiro.core.CustomDefaultFilterChainManager;
import team.kirohuji.shiro.core.CustomPathMatchingFilterChainResolver;
import team.kirohuji.shiro.core.CustomShiroFilterFactoryBean;
import team.kirohuji.shiro.core.StatelessDefaultSubjectFactory;
import team.kirohuji.shiro.credentials.RetryLimitHashedCredentialsMatcher;
import team.kirohuji.shiro.filter.JWTFilter;
import team.kirohuji.shiro.realm.DefaultModularRealm;
import team.kirohuji.shiro.realm.TokenRealm;
import team.kirohuji.shiro.realm.UserRealm;

@Configuration
public class ShiroConfig {

    @Bean("securityManager")
    public DefaultWebSecurityManager getManager() {
        DefaultWebSecurityManager manager = new DefaultWebSecurityManager();
        // 使用自己的realm
/*        manager.setRealm(userRealm());*/
        manager.setAuthenticator(defineModularRealmAuthenticator());
        ArrayList<Realm> lists=new ArrayList<>();
        lists.add(tokenRealm());
        manager.setRealms(lists);
        /*
         * 关闭shiro自带的session，详情见文档
         * http://shiro.apache.org/session-management.html#SessionManagement-StatelessApplications%28Sessionless%29
         */
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        manager.setSubjectDAO(subjectDAO);

        return manager;
    }
    @Bean
    public DefaultModularRealm defineModularRealmAuthenticator() {
    	DefaultModularRealm dmr=new DefaultModularRealm();
    	Map<String,Realm> definedRealms=new HashMap<>();
    	definedRealms.put("userRealm", userRealm());
    	definedRealms.put("tokenRealm", tokenRealm());
    	dmr.setDefinedRealms(definedRealms);
    	dmr.setAuthenticationStrategy(new FirstSuccessfulStrategy());
    	return dmr;
    }
    
	@Bean("subjectFactory")
	public DefaultWebSubjectFactory subjectFactory() {
		return new StatelessDefaultSubjectFactory();
	}
	
  //缓存管理器
  	@Bean
  	public CacheManager cacheManager() {
          EhCacheManager cacheManager = new EhCacheManager();
          cacheManager.setCacheManagerConfigFile("classpath:encache.xml");
  		return cacheManager;
  	}
      //凭证匹配器
  	@Bean
  	public CredentialsMatcher credentialsMatcher() {
  		RetryLimitHashedCredentialsMatcher rlcm = new RetryLimitHashedCredentialsMatcher(cacheManager());
  		rlcm.setHashAlgorithmName("md5");
  		rlcm.setHashIterations(252);
  		rlcm.setStoredCredentialsHexEncoded(true);
  		return rlcm;
  	}
  	@Bean
  	public Realm userRealm() {
  		UserRealm userRealm = new UserRealm();
  		userRealm.setCredentialsMatcher(credentialsMatcher());
  		userRealm.setCachingEnabled(false);
  		userRealm.setAuthenticationCachingEnabled(true);
  		userRealm.setAuthenticationCacheName("authenticationCache");
  		userRealm.setAuthorizationCacheName("authorizationCache");
  		userRealm.setAuthorizationCachingEnabled(true);
  		return userRealm;
  	}
  	@Bean
  	public Realm tokenRealm() {
  		TokenRealm tokenRealm = new TokenRealm();
  		return tokenRealm;
  	}
  	
	@Bean("filterChainResolver")
	public CustomPathMatchingFilterChainResolver filterChainResolver() {
		CustomPathMatchingFilterChainResolver filterChainResolver = new CustomPathMatchingFilterChainResolver();
		filterChainResolver.setCustomDefaultFilterChainManager(filterChainManager());
		return filterChainResolver;

	}

	@Bean("filterChainManager")
	public CustomDefaultFilterChainManager filterChainManager() {
		CustomDefaultFilterChainManager filterChainManager = new CustomDefaultFilterChainManager();
		System.out.println("在ShiroConfig的filterChainManager里配置过滤器的参数");
		filterChainManager.setLoginUrl("/sign/in?username=zyd&password=zyd");
		filterChainManager.setSuccessUrl("/");
		filterChainManager.setUnauthorizedUrl("/401");
		Map<String, Filter> filterMap = new HashMap<>();
		filterMap.put("jwt", new JWTFilter());
		filterChainManager.setCustomFilters(filterMap);
		Map<String, String> filterRuleMap = new HashMap<>();
		// 所有请求通过我们自己的JWT Filter
		filterRuleMap.put("/sign/in", "anon");
		// 访问401和404页面不通过我们的Filter
		filterRuleMap.put("/401", "anon");
		filterRuleMap.put("/404", "anon");
		filterRuleMap.put("/**", "jwt");
		filterChainManager.setFilterChainDefinitionMap(filterRuleMap);
		return filterChainManager;
	}
  	
    @Bean("shiroFilter")
    public ShiroFilterFactoryBean factory(DefaultWebSecurityManager securityManager) {
		CustomShiroFilterFactoryBean factoryBean = new CustomShiroFilterFactoryBean();
		factoryBean.setSecurityManager(securityManager);
		return factoryBean;
    }

    /**
     * 下面的代码是添加注解支持
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        return new DefaultAdvisorAutoProxyCreator();
    }

    @Bean
    public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
